'use client'

import React from 'react'
import { message, notification } from 'antd'
import {
    CheckCircleOutlined,
    CloseCircleOutlined,
    ExclamationCircleOutlined,
    InfoCircleOutlined,
    LoadingOutlined
} from '@ant-design/icons'
import { useNotifications } from './NotificationSystem'
import { useConfirmation } from './ConfirmationDialogs'

// 反馈类型
export type FeedbackType = 'success' | 'error' | 'warning' | 'info' | 'loading'

// 反馈配置
interface FeedbackConfig {
    type: FeedbackType
    title: string
    message?: string
    duration?: number
    placement?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight'
    showProgress?: boolean
    actions?: Array<{
        label: string
        onClick: () => void
        type?: 'primary' | 'default'
    }>
}

// 操作反馈管理器
export class FeedbackManager {
    private static instance: FeedbackManager
    private activeOperations = new Map<string, { type: string; startTime: number }>()

    private constructor() { }

    public static getInstance(): FeedbackManager {
        if (!FeedbackManager.instance) {
            FeedbackManager.instance = new FeedbackManager()
        }
        return FeedbackManager.instance
    }

    // 显示操作开始反馈
    public startOperation(operationId: string, operationType: string, title: string): void {
        this.activeOperations.set(operationId, {
            type: operationType,
            startTime: Date.now()
        })

        message.loading({
            content: title,
            key: operationId,
            duration: 0 // 不自动消失
        })
    }

    // 显示操作成功反馈
    public operationSuccess(
        operationId: string,
        title: string,
        description?: string,
        showNotification = true
    ): void {
        const operation = this.activeOperations.get(operationId)
        const duration = operation ? Date.now() - operation.startTime : 0

        // 更新消息
        message.success({
            content: title,
            key: operationId,
            duration: 2
        })

        // 显示详细通知
        if (showNotification) {
            notification.success({
                message: title,
                description: description || `操作成功完成${duration > 1000 ? ` (耗时 ${(duration / 1000).toFixed(1)}s)` : ''}`,
                placement: 'topRight',
                duration: 4
            })
        }

        this.activeOperations.delete(operationId)
    }

    // 显示操作失败反馈
    public operationError(
        operationId: string,
        title: string,
        error?: string | Error,
        showRetry = false,
        onRetry?: () => void
    ): void {
        const operation = this.activeOperations.get(operationId)
        const errorMessage = error instanceof Error ? error.message : error

        // 更新消息
        message.error({
            content: title,
            key: operationId,
            duration: 3
        })

        // 显示详细通知
        const actions = showRetry && onRetry ? [
            {
                label: '重试',
                onClick: onRetry,
                type: 'primary' as const
            }
        ] : undefined

        notification.error({
            message: title,
            description: errorMessage || '操作失败，请稍后重试',
            placement: 'topRight',
            duration: 6,
            btn: actions ? (
                <div className="space-x-2">
                    {actions.map((action, index) => (
                        <button
                            key={index}
                            onClick={action.onClick}
                            className={`
                                px-3 py-1 text-sm rounded transition-colors
                                ${action.type === 'primary'
                                    ? 'bg-blue-600 text-white hover:bg-blue-700'
                                    : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                                }
                            `}
                        >
                            {action.label}
                        </button>
                    ))}
                </div>
            ) : undefined
        })

        this.activeOperations.delete(operationId)
    }

    // 更新操作进度
    public updateOperationProgress(
        operationId: string,
        progress: number,
        title?: string
    ): void {
        const progressText = title || `处理中... ${Math.round(progress)}%`

        message.loading({
            content: progressText,
            key: operationId,
            duration: 0
        })
    }

    // 取消操作
    public cancelOperation(operationId: string): void {
        message.destroy(operationId)
        this.activeOperations.delete(operationId)
    }

    // 获取活动操作
    public getActiveOperations(): string[] {
        return Array.from(this.activeOperations.keys())
    }

    // 清除所有操作
    public clearAllOperations(): void {
        this.activeOperations.forEach((_, operationId) => {
            message.destroy(operationId)
        })
        this.activeOperations.clear()
    }
}

// 导出单例实例
export const feedbackManager = FeedbackManager.getInstance()

// 反馈系统Hook
export const useFeedback = () => {
    const notifications = useNotifications()
    const confirmation = useConfirmation()

    // 操作反馈
    const withFeedback = async <T,>(
        operation: () => Promise<T>,
        config: {
            startMessage: string
            successMessage: string
            errorMessage: string
            showProgress?: boolean
            onProgress?: (progress: number) => void
        }
    ): Promise<T> => {
        const operationId = `op_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`

        try {
            feedbackManager.startOperation(operationId, 'async', config.startMessage)

            const result = await operation()

            feedbackManager.operationSuccess(operationId, config.successMessage)
            return result
        } catch (error) {
            feedbackManager.operationError(
                operationId,
                config.errorMessage,
                error instanceof Error ? error : undefined
            )
            throw error
        }
    }

    // 文件上传反馈
    const withUploadFeedback = async <T,>(
        uploadOperation: (onProgress: (progress: number) => void) => Promise<T>,
        config: {
            startMessage?: string
            successMessage?: string
            errorMessage?: string
        } = {}
    ): Promise<T> => {
        const operationId = `upload_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`

        try {
            feedbackManager.startOperation(
                operationId,
                'upload',
                config.startMessage || '开始上传文件...'
            )

            const result = await uploadOperation((progress) => {
                feedbackManager.updateOperationProgress(
                    operationId,
                    progress,
                    `上传中... ${Math.round(progress)}%`
                )
            })

            feedbackManager.operationSuccess(
                operationId,
                config.successMessage || '文件上传成功'
            )

            return result
        } catch (error) {
            feedbackManager.operationError(
                operationId,
                config.errorMessage || '文件上传失败',
                error instanceof Error ? error : undefined,
                true, // 显示重试按钮
                () => withUploadFeedback(uploadOperation, config) // 重试逻辑
            )
            throw error
        }
    }

    // 数据处理反馈
    const withProcessingFeedback = async <T,>(
        processingOperation: () => Promise<T>,
        config: {
            dataType: string
            action: string
        }
    ): Promise<T> => {
        return withFeedback(processingOperation, {
            startMessage: `正在${config.action}${config.dataType}...`,
            successMessage: `${config.dataType}${config.action}成功`,
            errorMessage: `${config.dataType}${config.action}失败`
        })
    }

    // 快捷反馈方法
    const showSuccess = (message: string, description?: string) => {
        notifications.showSuccess(message, description)
    }

    const showError = (message: string, description?: string) => {
        notifications.showError(message, description)
    }

    const showWarning = (message: string, description?: string) => {
        notifications.showWarning(message, description)
    }

    const showInfo = (message: string, description?: string) => {
        notifications.showInfo(message, description)
    }

    // 操作确认反馈
    const confirmAndExecute = async (
        operation: () => Promise<void>,
        confirmConfig: {
            title: string
            content: string
            successMessage: string
            errorMessage: string
        }
    ): Promise<boolean> => {
        const confirmed = await confirmation.showConfirmation({
            type: 'warning',
            title: confirmConfig.title,
            content: confirmConfig.content
        })

        if (confirmed) {
            try {
                await withFeedback(operation, {
                    startMessage: '执行操作中...',
                    successMessage: confirmConfig.successMessage,
                    errorMessage: confirmConfig.errorMessage
                })
                return true
            } catch (error) {
                return false
            }
        }

        return false
    }

    return {
        withFeedback,
        withUploadFeedback,
        withProcessingFeedback,
        showSuccess,
        showError,
        showWarning,
        showInfo,
        confirmAndExecute,
        feedbackManager
    }
}

// 批量操作反馈
export const useBatchFeedback = () => {
    const feedback = useFeedback()

    const withBatchFeedback = async <T,>(
        items: T[],
        operation: (item: T, index: number) => Promise<void>,
        config: {
            itemName: string
            actionName: string
            batchSize?: number
        }
    ): Promise<{ success: number; failed: number; errors: Error[] }> => {
        const { itemName, actionName, batchSize = 10 } = config
        const total = items.length
        let success = 0
        let failed = 0
        const errors: Error[] = []

        const operationId = `batch_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`

        try {
            feedbackManager.startOperation(
                operationId,
                'batch',
                `开始批量${actionName}${itemName}...`
            )

            // 分批处理
            for (let i = 0; i < items.length; i += batchSize) {
                const batch = items.slice(i, i + batchSize)

                await Promise.allSettled(
                    batch.map(async (item, batchIndex) => {
                        try {
                            await operation(item, i + batchIndex)
                            success++
                        } catch (error) {
                            failed++
                            errors.push(error instanceof Error ? error : new Error(String(error)))
                        }
                    })
                )

                // 更新进度
                const progress = ((i + batch.length) / total) * 100
                feedbackManager.updateOperationProgress(
                    operationId,
                    progress,
                    `${actionName}中... ${success + failed}/${total}`
                )
            }

            // 显示结果
            if (failed === 0) {
                feedbackManager.operationSuccess(
                    operationId,
                    `批量${actionName}完成`,
                    `成功${actionName}了 ${success} 个${itemName}`
                )
            } else if (success === 0) {
                feedbackManager.operationError(
                    operationId,
                    `批量${actionName}失败`,
                    `所有${itemName}${actionName}失败`
                )
            } else {
                feedbackManager.operationSuccess(
                    operationId,
                    `批量${actionName}部分完成`,
                    `成功 ${success} 个，失败 ${failed} 个`
                )
            }

        } catch (error) {
            feedbackManager.operationError(
                operationId,
                `批量${actionName}出错`,
                error instanceof Error ? error : undefined
            )
        }

        return { success, failed, errors }
    }

    return { withBatchFeedback }
}

export default {
    FeedbackManager,
    feedbackManager,
    useFeedback,
    useBatchFeedback
}